﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DTO;
using BLL;

namespace HDT.GUI
{
    public partial class FrmThemPN : Form
    {
        private NhanVienDTO nhanVien;
        public delegate void MyDelegate();
        public MyDelegate refreshForm;

        List<ChiTietPhieuNhapDTO> dsChiTiet;

        public FrmThemPN()
        {
            InitializeComponent();
            dsChiTiet = new List<ChiTietPhieuNhapDTO>();
            nhanVien = new NhanVienDTO();
        }

        public FrmThemPN(DTO.NhanVienDTO nhanVien)
            : this()
        {
            // TODO: Complete member initialization
            this.nhanVien = nhanVien;
        }

        private void btnQuayLai_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void LoadCTPhieuNhapInfo(ChiTietPhieuNhapDTO chiTiet)
        {
            if (chiTiet == null)
            {
                ShowDetail(null);
                return;
            }

            foreach (ChiTietPhieuNhapDTO ct in dsChiTiet)
            {
                if ((ct.MaMatHang == chiTiet.MaMatHang)
                    && ((ct.HanSuDung == chiTiet.HanSuDung) 
                    || (ct.HanSuDung.Value.Date == chiTiet.HanSuDung.Value.Date)))
                {
                    ShowDetail(ct);
                    return;
                }
            }

        }

        private void ShowDetail(ChiTietPhieuNhapDTO chiTiet)
        {
            try
            {
                MatHangDTO matHang = new MatHangBLL().GetByID(chiTiet.MaMatHang);
                txtTenMH.Text = matHang.TenMatHang;
                txtDVT.Text = matHang.DonViTinh;
                try
                {
                    txtLoaiMH.Text = new LoaiMatHangBLL().GetByID(matHang.MaLoaiMatHang).TenLoaiMatHang;
                }
                catch
                {
                    txtLoaiMH.Clear();
                }
            }
            catch
            {
                txtTenMH.Clear();
                txtDVT.Clear();
                txtLoaiMH.Clear();
            }

            try
            {
                txtHSD.Text = (chiTiet.HanSuDung == null) ? "N/A" : chiTiet.HanSuDung.Value.ToString("dd/MM/yyyy");
                txtSL.Text = chiTiet.SoLuongNhap.ToString("#,##0");
                txtGia.Text = chiTiet.DonGiaNhap.ToString("#,##0");
            }
            catch
            {
                txtHSD.Clear();
                txtSL.Clear();
                txtGia.Clear();
            }
        }

        private void AddDSChiTietData()
        {
            dgvDSCT.Rows.Clear();
            foreach (ChiTietPhieuNhapDTO chiTiet in dsChiTiet)
            {
                DataGridViewRow row = (DataGridViewRow)dgvDSCT.Rows[0].Clone();
                row.Cells[0].Value = chiTiet.MaMatHang;
                row.Cells[1].Value = chiTiet.HanSuDung == null ? "N/A" : chiTiet.HanSuDung.Value.ToString("dd/MM/yyyy");
                row.Cells[2].Value = chiTiet.SoLuongNhap.ToString("#,##0");
                row.Cells[3].Value = chiTiet.DonGiaNhap.ToString("#,##0");
                dgvDSCT.Rows.Add(row);
            }
            
            btnThemPN.Enabled = !("".Equals(txtNhaCC.Text.Trim()) || dsChiTiet.Count == 0);
        }

        private void AddChiTiet(ChiTietPhieuNhapDTO chiTiet)
        {
            if (CheckChiTiet(chiTiet))
            {
                int length = dsChiTiet.Count;
                for (int i = 0; i < length; i++)
                {
                    if ((dsChiTiet[i].MaMatHang == chiTiet.MaMatHang)
                        && ((dsChiTiet[i].HanSuDung == chiTiet.HanSuDung)
                        || (dsChiTiet[i].HanSuDung.Value.Date == chiTiet.HanSuDung.Value.Date)))
                    {
                        DialogResult dialogResult = MessageBox.Show("Chi tiết mặt hàng này đã tồn tại trong phiếu. Bạn muốn cập nhật?", "CẢNH BÁO", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dialogResult == DialogResult.Yes)
                        {
                            dsChiTiet[i] = chiTiet;
                            AddDSChiTietData();
                        }
                        return;
                    }
                }
                dsChiTiet.Add(chiTiet);
                AddDSChiTietData();
            }
        }

        private bool CheckChiTiet(ChiTietPhieuNhapDTO chiTiet)
        {
            ThamSoDTO thamSo = new ThamSoBLL().GetThamSo();

            if (chiTiet.SoLuongNhap > thamSo.SLNhap)
            {
                MessageBox.Show("Số lượng nhập quá lớn.", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            int SLTon = new MatHangBLL().SoLuongTon(chiTiet.MaMatHang);
            if (SLTon > thamSo.SLTon)
            {
                MessageBox.Show("Số lượng tồn còn nhiều. Không thể nhập thêm", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        private void RemoveChiTiet(ChiTietPhieuNhapDTO chiTiet)
        {
            int length = dsChiTiet.Count;
            for (int i = 0; i < length; i++)
            {
                if ((dsChiTiet[i].MaMatHang == chiTiet.MaMatHang) 
                    && ((dsChiTiet[i].HanSuDung == chiTiet.HanSuDung) 
                    || (dsChiTiet[i].HanSuDung.Value.Date == chiTiet.HanSuDung.Value.Date)))
                {
                    dsChiTiet.RemoveAt(i);
                    AddDSChiTietData();
                    return;
                }
            }
        }

        private void dgvDSCT_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvDSCT.SelectedRows.Count > 0)
            {
                try
                {
                    ChiTietPhieuNhapDTO chiTiet = new ChiTietPhieuNhapDTO();
                    chiTiet.MaMatHang = dgvDSCT.SelectedRows[0].Cells[0].Value.ToString();
                    string HSD = dgvDSCT.SelectedRows[0].Cells[1].Value.ToString();
                    if (!HSD.Equals("N/A"))
                    {
                        chiTiet.HanSuDung = DateTime.ParseExact(HSD, "dd/MM/yyyy", null);
                    }
                    LoadCTPhieuNhapInfo(chiTiet);
                    btnXoaCK.Enabled = true;
                }
                catch
                {
                    LoadCTPhieuNhapInfo(null);
                    btnXoaCK.Enabled = false;
                }
            }
        }

        private void btnThemCK_Click(object sender, EventArgs e)
        {
            FrmThemCTPN f = new FrmThemCTPN();
            f.AddChiTiet = new FrmThemCTPN.MyDelegate(AddChiTiet);
            f.ShowDialog();
        }

        private void btnXoaCK_Click(object sender, EventArgs e)
        {
            try
            {
                ChiTietPhieuNhapDTO chiTiet = new ChiTietPhieuNhapDTO();
                chiTiet.MaMatHang = dgvDSCT.SelectedRows[0].Cells[0].Value.ToString();
                string HSD = dgvDSCT.SelectedRows[0].Cells[1].Value.ToString();
                if (!HSD.Equals("N/A"))
                {
                    chiTiet.HanSuDung = DateTime.ParseExact(HSD, "dd/MM/yyyy", null);
                }
                RemoveChiTiet(chiTiet);
            }
            catch
            {

            }
        }

        private void NewPhieuNhap(ref PhieuNhapDTO phieuNhap)
        {
            phieuNhap.NhaCungCap = txtNhaCC.Text.Trim();
            phieuNhap.ThoiGian = dtmNgayLap.Value;
            phieuNhap.MaNhanVien = nhanVien.MaNhanVien;
            new PhieuNhapBLL().Insert(phieuNhap);
            phieuNhap = new PhieuNhapBLL().GetLast();
        }

        private void NewCTPhieuNhap(PhieuNhapDTO phieuNhap)
        {
            int length = dsChiTiet.Count;
            for (int i = 0; i < length; i++)
            {
                dsChiTiet[i].MaPhieuNhap = phieuNhap.MaPhieu;
            }
            new ChiTietPhieuNhapBLL().Insert(dsChiTiet);
        }

        private void btnThemPN_Click(object sender, EventArgs e)
        {
            try
            {
                PhieuNhapDTO phieu = new PhieuNhapDTO();
                NewPhieuNhap(ref phieu);
                NewCTPhieuNhap(phieu);
                MessageBox.Show("Lập phiếu nhập thành công", "THÔNG BÁO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                refreshForm();
                this.Dispose();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtNhaCC_TextChanged(object sender, EventArgs e)
        {
            btnThemPN.Enabled = !("".Equals(txtNhaCC.Text.Trim()) || dsChiTiet.Count == 0);
        }

        private void FrmThemPN_Load(object sender, EventArgs e)
        {
            txtNVLap.Text = nhanVien.MaNhanVien;
        }
    }
}
